import React, { useState, FC } from 'react';
import { Form, Input, Radio, Select, Modal, Button, Table } from 'antd';
import { columns, fieldColumns } from './data';
import type { DataType, TaskListenerType, FieldDataType } from './data.d';

const { Option } = Select;

const TaskListener = (props: TaskListenerType) => {
  const { currentElement, modeler } = props;
  const [form] = Form.useForm();
  const [fieldForm] = Form.useForm();
  // 控制添加弹框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 监听表格
  const [tableData, setTableData] = useState<DataType[]>([]);
  // 监听表格
  const [fieldTableData, setFieldTableData] = useState<FieldDataType[]>([]);
  // 控制注入字段弹框
  const [isFieldModalOpen, setIsFieldModalOpen] = useState(false);
  // 编辑key
  const [editKey, setEditKey] = useState('');
  // 保留项
  const [reservedItem, setReservedItem] = useState([]);

  React.useEffect(() => {
    if (currentElement?.businessObject?.extensionElements) {
      let reserved =
        currentElement?.businessObject?.extensionElements?.values.filter(
          (item: any) => {
            return item.$type.indexOf('ExecutionListener') == -1;
          },
        );
      setReservedItem(reserved);
      let arr = currentElement?.businessObject?.extensionElements?.values
        .filter((item: any) => {
          return item.$type.indexOf('TaskListener') != -1;
        })
        .map((item: any) => {
          let obj: DataType = {
            key: '',
            event: item.event,
            type: '',
            value: '',
            field: [],
          };
          for (const key in item) {
            switch (key) {
              case 'class':
                obj.type = 'class';
                obj.value = item[key];
                obj.key = obj.event + obj.type + obj.value;
                break;
              case 'expression':
                obj.type = 'expression';
                obj.value = item[key];
                obj.key = obj.event + obj.type + obj.value;
                break;
              case 'delegateExpression':
                obj.type = 'delegateExpression';
                obj.value = item[key];
                obj.key = obj.event + obj.type + obj.value;
                break;
              default:
                break;
            }
          }
          obj.field = item.fields?.map((i: any) => {
            return {
              key: i.name + (i.string ? 'string' : null) + i.string?.body,
              name: i.name,
              type: i.string ? 'string' : null,
              value: i.string?.body,
            };
          });
          return obj;
        });
      setTableData(arr);
    }
  }, [currentElement]);

  // 监听器表格编辑
  const editing = (record: any) => {
    let formData = {
      event: record.event,
      listener: {
        type: record.type,
        value: record.value,
      },
    };
    setEditKey(record.key);
    setFieldTableData(record.field);
    form.setFieldsValue(formData);
    setIsModalOpen(true);
  };

  // 删除表格
  const del = (record: any) => {
    let data = tableData.filter((item) => {
      return item.key != record.key;
    });
    setTableData(data);
  };

  // 监听器类型自定义
  const typeRender: any = (text: any, record: any, index: number) => {
    switch (text) {
      case 'class':
        return '类';
      case 'expression':
        return '表达式';
      case 'delegateExpression':
        return '委托表达式';
      default:
        break;
    }
  };
  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a onClick={() => editing(record)}>编辑</a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a onClick={() => del(record)}>删除</a>
      </li>
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
    item.dataIndex === 'type' ? (item.render = typeRender) : undefined;
  });

  // 打开监听模态框
  const showModal = () => {
    form.resetFields();
    setFieldTableData([]);
    setIsModalOpen(true);
  };

  // 注入字段模态框
  const showFieldModal = () => {
    fieldForm.resetFields();
    setIsFieldModalOpen(true);
  };

  // 字段模态框确定按钮
  const handleFieldOk = async () => {
    const values = await fieldForm.validateFields();
    let obj: FieldDataType = {
      key: values.name + values.value,
      name: values.name,
      value: values.field.value,
    };
    let data: FieldDataType[] = [...fieldTableData];
    data.push(obj);
    setFieldTableData(data);
    setIsFieldModalOpen(false);
  };

  // 监听模态框取消按钮
  const handleFieldCancel = () => {
    setIsFieldModalOpen(false);
  };

  // 监听模态框确定按钮
  const handleOk = async () => {
    const values = await form.validateFields();
    let obj: DataType = {
      key: values.event + values.listener.type + values.listener.value,
      event: values.event,
      type: values.listener.type,
      value: values.listener.value,
      field: fieldTableData,
    };
    let data: DataType[] = [...tableData];
    if (editKey != '') {
      data.filter((item, index) => {
        if (item.key == editKey) {
          data[index] = obj;
        }
      });
    } else {
      data.push(obj);
    }
    setEditKey('');
    setTableData(data);
    save(data);
    setIsModalOpen(false);
  };

  // 监听模态框取消按钮
  const handleCancel = () => {
    setEditKey('');
    setIsModalOpen(false);
  };

  // 保存监听器
  const save = (data: any) => {
    let extensionElements =
      currentElement.businessObject.get('extensionElements');
    if (!extensionElements) {
      extensionElements = modeler
        .get('moddle')
        .create('bpmn:ExtensionElements');
      currentElement.businessObject.extensionElements = extensionElements;
    }
    currentElement.businessObject.extensionElements.values = reservedItem;
    data.map((item: any) => {
      const executeListener = modeler
        .get('moddle')
        .create('flowable:TaskListener');
      executeListener['event'] = item.event;
      executeListener[item.type] = item.value;
      executeListener.fields = [];
      item.field?.map((i: any) => {
        const field = modeler.get('moddle').create(`flowable:Field`);
        field['name'] = i.name;
        field['string'] = modeler.get('moddle').create(`flowable:string`);
        field['string'].body = i.value;
        executeListener.fields.push(field);
      });
      currentElement.businessObject.extensionElements.values.push(
        executeListener,
      );
    });
  };

  return (
    <>
      <Table columns={columns} dataSource={tableData} rowKey="key"></Table>
      <Button
        type="primary"
        onClick={showModal}
        style={{ marginTop: 10 }}
        block
      >
        添加监听器
      </Button>
      <Modal
        okText="确定"
        cancelText="取消"
        title="添加监听器"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form}>
          <Form.Item label="事件类型" name="event">
            <Select placeholder="请选择事件类型">
              <Option value="create">create</Option>
              <Option value="assignment">assignment</Option>
              <Option value="complete">complete</Option>
              <Option value="delete">delete</Option>
            </Select>
          </Form.Item>
          <Form.Item label="监听器">
            <Input.Group compact>
              <Form.Item name={['listener', 'type']} noStyle>
                <Select style={{ width: '30%' }} placeholder="请选择监听器类型">
                  <Option value="class">类</Option>
                  <Option value="expression">表达式</Option>
                  <Option value="delegateExpression">委托表达式</Option>
                </Select>
              </Form.Item>
              <Form.Item name={['listener', 'value']} noStyle>
                <Input style={{ width: '70%' }} placeholder="请填写监听器值" />
              </Form.Item>
            </Input.Group>
          </Form.Item>
        </Form>
        <Table
          title={() => '注入字段:'}
          columns={fieldColumns}
          dataSource={fieldTableData}
          rowKey="key"
        ></Table>
        <Button
          type="primary"
          onClick={showFieldModal}
          style={{ marginTop: 10 }}
          block
        >
          注入字段
        </Button>
        <Modal
          okText="确定"
          cancelText="取消"
          title="注入字段"
          open={isFieldModalOpen}
          onOk={handleFieldOk}
          onCancel={handleFieldCancel}
        >
          <Form form={fieldForm}>
            <Form.Item label="字段名称" name="name">
              <Input placeholder="请填写字段名称" />
            </Form.Item>
            <Form.Item label="字段值" name="value">
              <Input placeholder="请填写字段值" />
            </Form.Item>
          </Form>
        </Modal>
      </Modal>
    </>
  );
};

export default TaskListener;
